<?php
/**
 * This file is part of easycrm.
 * Author: louxin
 * Date: 14/12/17
 * Time: 15:08
 * File: LogHelper.php
 */

namespace Icsoc\CoreBundle\Logger;

use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class ActionLogger
 * @package Icsoc\CoreBundle\Logger
 */
class ActionLogger
{
    const ACTION_NONE = 0;
    const ACTION_LOGIN = 1;
    const ACTION_LOGOUT = 2;
    const ACTION_ADD = 3;
    const ACTION_UPDATE = 4;
    const ACTION_DELETE = 5;

    /** @var  ContainerInterface $container */
    private $container;

    /** @var array 有效的操作类型 */
    private $validActionType = array(1, 2, 3, 4, 5);

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * 记录操作日志
     *
     * @param int $actionType 操作类型，1-login,2-logout,3-add,4-update,5-delete
     * @param string $logString 操作日志
     *
     * @return bool
     */
    public function actionLog($actionType, $logString)
    {
        if (empty($logString)) {
            return false;
        }

        if (!in_array($actionType, $this->validActionType)) {
            return false;
        }

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get('doctrine.dbal.default_connection');
        /** @var  $request \Symfony\Component\HttpFoundation\Request */
        $request = $this->container->get('request');
        $user = $this->container->get('security.token_storage')->getToken()->getUser();
        $flag = $user->getFlag();
        //不记录系统管理人员；
        if ($flag != 'ccadmin') {
            $userNum = $flag == 'ccod' ? '管理员:' : '用户:';
            $username = $flag == 'ccod' ? $user->getAdminName() : $user->getAgName();
            $userNum.=$user->getUserNum().'['.$username.']';
            $data = array(
                'user_id' => $user->getUserId(),
                'user_num' => $userNum,
                'vcc_id' => $user->getVccId(),
                'vcc_code' => $user->getVccCode(),
                'action' => $actionType,
                'content' => $logString,
                'acttime' => time(),
                'actip' => $request->getClientIp()
            );
            if ($conn->insert('cc_logs', $data)) {
                return true;
            } else {
                $logger = $this->container->get('logger');
                $logger->error(
                    $this->container->get('translator')->trans(
                        'Log action type %actionType% content %logString% failed!',
                        array(
                            '%actionType%' => $actionType,
                            '%logString%' => $logString
                        )
                    )
                );
            }
        }
        return false;
    }
}
